import { isObject, isReservedTag } from "../util/index.js";
// 定义Vnode类
export default class Vnode {
  constructor(tag, data, key, children, text) {
    this.tag = tag;
    this.data = data;
    this.key = key;
    this.children = children;
    this.text = text;
  }
}

// 创建元素vnode 等于render函数里面的 h=>h(App)
export function createElement(vm, tag, data = {}, ...children) {
  let key = data.key;
  if(isReservedTag(tag)) {
    // 原生标签
    return new Vnode(tag, data, key, children);
  }else {
    // 组件
    console.log(vm);
    let Ctor = vm.$options.components[tag]
    createComponent(vm, tag, data, key, children, Ctor)
  }
  
}
function createComponent(vm, tag, data, key, children, Ctor) {
  if(isObject(Ctor)) {
    Ctor = vm.$options._base.extend(Ctor)
  }
  Ctor.hook = {
    init(vnode) {
      let child = (vnode.componentInstance = new Ctor({ _isComponent: true })); //实例化组件
      child.$mount();
    }
  }
   // 组件vnode  也叫占位符vnode  ==> $vnode
   return new Vnode(
    `vue-component-${Ctor.cid}-${tag}`,
    data,
    key,
    undefined,
    undefined,
    {
      Ctor,
      children,
    }
  );

}

// 创建文本vnode
export function createTextNode(text) {
  return new Vnode(undefined, undefined, undefined, undefined, text);
}
